package com.bt.bodyscale.activitys;

import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bt.bodyscale.B_MainActivity;
import com.bt.bodyscale.R;
import com.bt.bodyscale.configs.ScaleAppConfigs;
import com.ebelter.btcomlib.bases.activity.BaseActivity;
import com.ebelter.btcomlib.common.Constants;
import com.ebelter.btcomlib.models.beans.ScaleUser;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.models.https.interfaces.HttpResponse;
import com.ebelter.btcomlib.models.https.responses.LoginResponse;
import com.ebelter.btcomlib.utils.NumUtils;
import com.ebelter.btcomlib.utils.StatusBarUtil;
import com.ebelter.btcomlib.utils.StringUtils;
import com.ebelter.btcomlib.utils.ToastUtil;
import com.ebelter.btcomlib.utils.UserSpUtil;
import com.ebelter.btcomlib.utils.activity_manager.ActivityManagers;
import com.ebelter.btcomlib.utils.log.LogUtils;
import java.util.Calendar;


/**
 * 登录页
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {
    private final String TAG = "LoginActivity";


    EditText et_name_login;
    EditText et_pwd_login;

    TextView btn_login;
    TextView tv_forgot_password;
    TextView tv_join_us_free;

//    @BindView(R.id.login_mypsw_cb)
//    MyPswEd login_mypsw_cb;


    @Override
    protected int loadLayoutById() {
        return R.layout.activity_login;
    }


    @Override
    protected void initView() {
        StatusBarUtil.setDarkStatusIcon(this, ScaleAppConfigs.darkStatusIcon);
        FV();
      //  StatusBarUtil.setTranslucent(this, 0);
    }

    private void FV() {
        et_name_login=findViewById(R.id.et_name_login);
        et_pwd_login=findViewById(R.id.et_pwd_login);

        btn_login=findViewById(R.id.btn_login);
        tv_forgot_password=findViewById(R.id.tv_forgot_password);
        tv_join_us_free=findViewById(R.id.tv_join_us_free);

        btn_login.setOnClickListener(this);
        tv_forgot_password.setOnClickListener(this);
        tv_join_us_free.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        long user_id = UserSpUtil.readLong(Constants.IUser.USER_ID,-1);
        String nick_name = UserSpUtil.readString(Constants.IUser.NICK_NAME);
        String btid = UserSpUtil.readString(Constants.IUser.BT_ID);



        LogUtils.i(TAG,"----LoginActivity---A"+user_id);
        if (user_id>0&&!TextUtils.isEmpty(nick_name)&&!TextUtils.isEmpty(btid)){
            //说明已经登录了 直接登录吧
            //startActivity(MainActivity.class);
            finish();
        }
    }





    //登录
    private void sign_in() {
        String name = et_name_login.getText().toString().trim();
       String psw = et_pwd_login.getText().toString().trim();
      //  String psw = login_mypsw_cb.getText();

        if (TextUtils.isEmpty(name)){
            ToastUtil.show(R.string.Nikename_cannot_be_empty);
            return;
        }
        if (TextUtils.isEmpty(psw)){
            ToastUtil.show(R.string.The_password_cannot_be_empty);
            return;
        }
        if (!NetUtils.available()){
            ToastUtil.show(R.string.Network_error);
            return;
        }

        showLoadingDialog(StringUtils.getResStr(R.string.Log_in));

        NetUtils.getInstance().loginRequest(this, name,psw, new HttpResponse<LoginResponse>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, LoginResponse loginResponse, String s) {
                if (!isRequestSuccess){
                    ToastUtil.show(R.string.Network_connection_error);
                    return;
                }
                if (loginResponse.resultCode==0){
                    //登录成功
                    saveUserDatas(loginResponse.getResultData());
                    startActivity(B_MainActivity.class);
                    ActivityManagers.getInstance().closeActivity(B_SplashActivity.TAG);//关闭B_SplashActivity界面
                    finish();
                }else if (loginResponse.getResultCode()==109){//109是：不存在的email或者昵称
                    ToastUtil.show(R.string.mail_nickname_no_exist);
                }else if(loginResponse.getResultCode()==111){//111密码错误
                    ToastUtil.show(R.string.psw_error);
                }else if (loginResponse.getResultCode()==110){//服务器异常
                    ToastUtil.show(R.string.An_exception_occurred_on_the_server);
                }



            }
        });




    }


    public static String userid2btid(long user_id){
        if (user_id<0){
            user_id=0;
        }
        String userid=user_id+"";
        if (userid.length()>14){
            userid=userid.substring(userid.length()-14,userid.length());
        }
        return userid;
    }



    //保存登录用户数据
    private void saveUserDatas(LoginResponse.ResultDataBean resultData) {
        UserSpUtil.removeAll();

        LogUtils.i(TAG,"----------"+resultData.toString());

        long useridlong = resultData.getUserId();
        UserSpUtil.writeLong(Constants.IUser.USER_ID,useridlong);

        // TODO: 2018/4/23 zcq
        String btId = ScaleUser.getUser().toBtId(userid2btid(useridlong));
        LogUtils.i(TAG, "-----loginSave--useridlong = " + useridlong);
        LogUtils.i(TAG, "-----loginSave--btId = " + btId);

        UserSpUtil.writeString(Constants.IUser.BT_ID,btId);
        UserSpUtil.writeString(Constants.IUser.NICK_NAME,resultData.getNickName());
        UserSpUtil.writeString(Constants.IUser.EMAIL,resultData.getEmail());
        UserSpUtil.writeInt(Constants.IUser.HEIGHT,resultData.getHeight());
        UserSpUtil.writeFloat(Constants.IUser.WEIGHT,resultData.getWeight());

        String birthday=resultData.getBirthday();
        UserSpUtil.writeString(Constants.IUser.BIRTHDAY,birthday);
        int year=getBirthdayIntValue(birthday,0,1990);
        UserSpUtil.writeInt(Constants.IUser.YEAR,year);
        UserSpUtil.writeInt(Constants.IUser.MONTHS,getBirthdayIntValue(birthday,1,6));
        UserSpUtil.writeInt(Constants.IUser.DAY,getBirthdayIntValue(birthday,2,1));
        UserSpUtil.writeInt(Constants.IUser.AGE,getAgeByBirthday(year));


        UserSpUtil.writeInt(Constants.IUser.SEX,resultData.getSex());
        UserSpUtil.writeInt(Constants.IUser.PROFESSION,resultData.getProfession());
        UserSpUtil.writeFloat(Constants.IUser.IMPEDANCE,resultData.getImpedance());
        UserSpUtil.writeString(Constants.IUser.CREATEDATE,resultData.getCreateDate());
        UserSpUtil.writeString(Constants.IUser.UPDATEDATE,resultData.getUpdateDate());
        UserSpUtil.writeFloat(Constants.IUser.TARGET_WEIGHT,resultData.getTargetWeight());


    }

    private int getAgeByBirthday(int year){
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.YEAR)-year;
    }

    private int getBirthdayIntValue(String string,int index,int defaultValue){
        if (TextUtils.isEmpty(string)){
            return defaultValue;
        }
        String[] args = string.split("-");
        if (args.length!=3){
            return defaultValue;
        }
        return NumUtils.string2Int(args[index],defaultValue);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login://sign_in 登录
                sign_in();
                break;
            case R.id.tv_forgot_password://忘记密码
                //  startActivity(FindPswActivity.class);
                break;
            case R.id.ll_facebook:
                LogUtils.i(TAG,"----------facebook");
                //StatusBarUtil.setTranslucent(this, 0);
                //StatusBarUtil.setDarkStatusIcon(this,true);
                break;
            case R.id.ll_twitter:
                LogUtils.i(TAG,"----------twitter");
                //StatusBarUtil.setTranslucent(this, 0);
                //StatusBarUtil.setDarkStatusIcon(this,false);
                // Intent intentw = new Intent(LoginActivity.this,CeshiActivity.class);
                // startActivity(intentw);

                break;
            case R.id.ll_line:
                // ToastUtil.show("测试界面");
                //Intent intent = new Intent(LoginActivity.this,CeshiActivity.class);
//                Intent intent = new Intent(LoginActivity.this,ModifyActivity.class);
//                intent.putExtra(ModifyActivity.MODIFY_STYLE,ModifyActivity.MODIFY_NAME);
//                intent.putExtra(ModifyActivity.DISPLAY_VALUE,"测试值");
                //   startActivity(intent);
                break;
            case R.id.tv_join_us_free:
                // startActivity(new Intent(this, RegisterActivity.class));
                break;
        }

    }
}
